package com.talkology.pilot.start.shiro.controller;

import com.talkology.pilot.database.model.SysRole;
import com.talkology.pilot.database.model.SysUser;
import com.talkology.pilot.start.shiro.service.ILoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private ILoginService loginService;

    //退出的时候是get请求，主要是用于退出
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "please login!";
    }

    //post登录
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestBody Map map) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                map.get("username").toString(),
                map.get("password").toString());
        usernamePasswordToken.setRememberMe(true);
        Session session = subject.getSession();
        //设置过期时间为10小时
        session.setTimeout(36000000);
        //进行验证，这里可以捕获异常，然后返回对应信息
        try {
            subject.login(usernamePasswordToken);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return "login success!";
    }

    //首页
    @RequestMapping(value = "/index")
    @ResponseBody
    public String index() {
        return "index";
    }

    //登出
    @RequestMapping(value = "/logout")
    @ResponseBody
    public String logout() {
        return "logout";
    }

    //错误页面展示，现在暂时弃用
//    @RequestMapping(value = "/error",method = RequestMethod.POST)
//    @ResponseBody
//    public String error(){
//        return "error ok!";
//    }

    //数据初始化
    @RequestMapping(value = "/addUser")
    @ResponseBody
    public String addUser(@RequestBody SysUser sysUser) {
        loginService.addSysUser(sysUser);
        return "addUser is ok! \n";
    }

    //注解的使用
    @RequiresRoles("1")
    @RequiresPermissions("create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public String create() {
        return "Create success!";
    }
}
